package com.easysoft.commons.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

/**
 * Properties文件加载工具
 * 
 * @author try
 * @version 1.0
 */

	public class PropertyConfig {

		private final static Logger logger = LoggerFactory.getLogger(PropertyConfig.class);

		private static Properties properties = new Properties();

		public PropertyConfig() {
		}

		public static Enumeration<Object> keys() {
			return properties.keys();
		}

		public static Set<Object> keySet() {
			return properties.keySet();
		}

		public static String getProperty(String key, String defaultValue) {
			String val = getProperty(key);
			return (val == null) ? defaultValue : val;
		}

		public static String getProperty(String key) {
			return properties.getProperty(key);
		}

		static {
			logger.info("============================== {} start loading ==============================", "commons.properties");
			InputStream inStream = getResourceAsStream(getContextClassLoader(), "commons.properties");

			try {
				if (inStream != null) {
					properties.load(inStream);

					if (logger.isDebugEnabled()) {
						Iterator<Entry<Object, Object>> it = properties.entrySet().iterator();
						while (it.hasNext()) {
							Entry<Object, Object> entry = it.next();
							logger.debug("load commons.properties : {} = {}", ObjectUtils.toString(entry.getKey()), ObjectUtils.toString(entry.getValue()));
						}
					}

					logger.info("============================== {} load successfully ==============================", "commons.properties");
				}
				else {
					logger.error("============================== {} load failed ==============================", "commons.properties");
				}
			}
			catch (IOException ex) {
				logger.error("============================== {} load IOException==============================", "commons.properties");
				logger.error(ex.getMessage());
			}
			finally {
				if (inStream != null)
					try {
						inStream.close();
					}
					catch (IOException ex) {
						ex.printStackTrace();
					}
			}
		}

		@SuppressWarnings({ "unchecked", "rawtypes" })
		private static InputStream getResourceAsStream(final ClassLoader loader, final String name) {
			return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
				public Object run() {
					if (loader != null) {
						return loader.getResourceAsStream(name);
					}
					else {
						return ClassLoader.getSystemResourceAsStream(name);
					}
				}
			});
		}

		private static ClassLoader getContextClassLoader() {
			ClassLoader classLoader = null;
			try {
				classLoader = Thread.currentThread().getContextClassLoader();
			}
			catch (SecurityException ex) {
				ex.printStackTrace();
			}
			return classLoader;
		}
}
